﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Web.Configuration;

namespace WXYW
{
    public partial class BJXXConfirmReturn : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindForms();
            }
        }

        private void BindForms()
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            if (!product.ApplicationForm.UserReference.IsLoaded)
            {
                product.ApplicationForm.UserReference.Load();
            }
            if (!product.ProductTypeReference.IsLoaded)
            {
                product.ProductTypeReference.Load();
            }

            contactLabel.Text = product.ApplicationForm.User.ContactPerson;
            companyLabel.Text = product.ApplicationForm.User.CompanyName;
            phoneNumberLabel.Text = product.ApplicationForm.User.UserPhone;
            cellPhoneLabel.Text = product.ApplicationForm.User.UserMobilePhone;
            faxLabel.Text = product.ApplicationForm.User.UserFax;
            addressLabel.Text = product.ApplicationForm.User.UserAddress;
            emailLabel.Text = product.ApplicationForm.User.UserEmail;
            agentLabel.Text = product.ApplicationForm.ProviderName;
            Label1.Text = product.ApplicationForm.ApplicationDateTime.Value.ToString("yyyy-MM-dd");
            Label2.Text = product.DealWithDateTime.HasValue ? product.DealWithDateTime.Value.ToString("yyyy-MM-dd") : "";
            emailTxtBox.Text = product.ApplicationForm.User.UserEmail;

            //
            runningNumberLabel.Text = product.ApplicationForm.RunningNumber;
            spcodeLabel.Text = product.SPCode;
            productTypeLabel.Text = product.ProductType.ProductTypeName;
            productSerivalNumberLabel.Text = product.ProductSerialNumber;
            sendTimeLabel.Text = product.DealWithDateTime.Value.ToString("yyyy-MM-dd");
            buyTimeLabel.Text = product.ProductPurchaseDateTime.Value.ToString("yyyy-MM-dd");
            statusLabel.Text = product.Status;
            repairTupeLabel.Text = product.ProductRepairType;
            clientReceiveMarkLabel.Text = product.BJXXClientReceiveMark;
            clientReceiveTimeLabel.Text = product.BJXXClientReceive.Value.ToString("yyyy-MM-dd");
            UserService userservice = new UserService();
            if (product.ApplicationForm.AgentID.HasValue)
            {
                User agent = userservice.GetUserByID(product.ApplicationForm.AgentID.Value);
                Label3.Text = agent.ContactPerson;
                Label4.Text = agent.UserPhone;
                applierPhoneTxtBox.Text = agent.UserMobilePhone;
            }
            else
            {
                applierPhoneTxtBox.Text = product.ApplicationForm.User.UserMobilePhone;
            }
            customerPhoneTxtBox.Text = product.ApplicationForm.User.UserMobilePhone;
            returnProductTypeTextBox.Text = product.ProductType.ProductTypeName;
            returnProductSerialTextBox.Text = product.ProductSerialNumber;
            returnProductVersionTextBox.Text = product.ProductVersionNumber;


            // bind last send product information
            if (product.ApplicationForm.ParentBJXXNO.HasValue)
            {
                ApplicationService appservice = new ApplicationService();
                ApplicationForm parentForm = appservice.GetApplicationFormByID(product.ApplicationForm.ParentBJXXNO.Value);
                if (parentForm != null && !parentForm.ApplicationProduct.IsLoaded)
                {
                    parentForm.ApplicationProduct.Load();
                }

                if (parentForm.ApplicationProduct.Count > 0)
                {
                    lastproductserialnumberTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().ReplaceProductSerialNumber;
                    lastproducttypeTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().ReplaceProductType;
                    lastproductVersionTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().ReplaceProductVersion;
                    lastsendRemarkTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().Remark;
                }

                reSendPanel.Visible = true;
            }

            emailNoticeTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXReturnEmailBody"], product.ApplicationForm.User.ContactPerson,
                product.ApplicationForm.ApplicationDateTime.Value.Month, product.ApplicationForm.ApplicationDateTime.Value.Day, product.ApplicationForm.ApplicationType.Equals("BB")?"备件先行":"DOA",
                product.ApplicationForm.ApplicationCode);
            SMS2ApplierTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXReturnSMS2ApplierBody"],
                product.ApplicationForm.ApplicationDateTime.Value.Month, product.ApplicationForm.ApplicationDateTime.Value.Day, product.ApplicationForm.ApplicationType.Equals("BB") ? "备件先行" : "DOA",
                product.ApplicationForm.ApplicationCode);
            SMS2CustomerTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXReturnSMS2CustomerBody"],
                product.ApplicationForm.ApplicationDateTime.Value.Month, product.ApplicationForm.ApplicationDateTime.Value.Day, product.ApplicationForm.ApplicationType.Equals("BB") ? "备件先行" : "DOA",
                product.ApplicationForm.ApplicationCode);
            SMS2SaleTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXReturnSMS2SaleBody"], product.ApplicationForm.User.CompanyName,
                product.ApplicationForm.ApplicationDateTime.Value.Month, product.ApplicationForm.ApplicationDateTime.Value.Day, product.ApplicationForm.ApplicationType.Equals("BB") ? "备件先行" : "DOA",
                product.ApplicationForm.ApplicationCode);
        }

        protected void reSendLinkButton_Click(object sender, EventArgs e)
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            if (!product.ApplicationForm.UserReference.IsLoaded)
            {
                product.ApplicationForm.UserReference.Load();
            }


            ApplicationService appService = new ApplicationService();
            ApplicationForm newForm = new ApplicationForm();
            newForm.ApplicationDateTime = product.ApplicationForm.ApplicationDateTime;
            //newForm.ApplicationCode = RunningNumberService.GenerateBJXXCode();
            //newForm.ApplicationCode = RunningNumberService.getr
            newForm.ApplicationType = product.ApplicationForm.ApplicationType;


            newForm.User = product.ApplicationForm.User;
            newForm.IsSubmit = product.ApplicationForm.IsSubmit;
            newForm.Status = product.ApplicationForm.Status;
            newForm.RunningNumber = RunningNumberService.GenerateApplicationNumber();
            newForm.ParentBJXXNO = product.ApplicationForm.ApplicationID;
            newForm.AgentID = product.ApplicationForm.AgentID;

            if (!product.ProductTypeReference.IsLoaded)
            {
                product.ProductTypeReference.Load();
            }
            if (!product.ProblemTypeReference.IsLoaded)
            {
                product.ProblemTypeReference.Load();
            }

            ApplicationProduct newproduct = new ApplicationProduct
            {
                ProductType = product.ProductType,
                ProductCount = product.ProductCount,
                ProductSerialNumber = product.ProductSerialNumber,
                ProductVersionNumber = product.ProductVersionNumber,
                ProblemType = product.ProblemType,
                ProductProblemDescription = product.ProductProblemDescription,
                ProductAppearance = product.ProductAppearance,
                ProductPurchaseDateTime = product.ProductPurchaseDateTime,
                ProductRepairType = product.ProductRepairType,
                SPCode = RunningNumberService.GenerateBJXXCode(),
                Status = "已审批-待发货",
                BJXXApproveComment = product.BJXXApproveComment,
                BJXXDealResult = product.BJXXDealResult,
                DealWithDateTime = product.DealWithDateTime,
                DealUserID = product.DealUserID
            };

            newForm.ApplicationProduct.Add(newproduct);

            long applicationID = appService.AddApplication(newForm);

            appService.SubmitApplication(applicationID);

            Response.Write(string.Format("<script language='JavaScript'> alert( '已产生一个新单在待发货下');location.href= 'BJXXListNeedConfirmReturn.aspx' </script>"));
        }

        protected void saveLinkButton_Click(object sender, EventArgs e)
        {
            ProductClassService classService = new ProductClassService();
            ProductType type = classService.GetProductTypeByName(returnProductTypeTextBox.Text);
            if (type == null)
            {
                msgLbl.Text = "填写归还产品型号不存在，请检查是否正确。";
            }
            else
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
                product.Status = "备件已归还待派单";
                product.BJXXReturnBack = DateTime.Now;
                product.ReturnRemark = returnRemarkTextBox.Text;
                product.ReturnSerialNumber = returnProductSerialTextBox.Text;
                product.ReturnProductType = returnProductTypeTextBox.Text;
                product.ReturnProductVersion = returnProductVersionTextBox.Text;
                //product.ProductSerialNumber = returnProductSerialTextBox.Text;
                //product.ProductType=service.getproduct
                service.UpdateProduct(product);
                // 入库

                //ApplicationService appService = new ApplicationService();
                //UserService userservice = new UserService();
                //WXYW.DAL.User userentity = userservice.GetUserByName(System.Configuration.ConfigurationManager.AppSettings["BJKF"].ToString());
                //ApplicationForm newForm = new ApplicationForm();
                //newForm.ApplicationDateTime = DateTime.Now;
                ////newForm.ApplicationCode = RunningNumberService.getr
                //newForm.ApplicationType = "R";
                //newForm.User = userentity;
                //newForm.IsSubmit = true;
                //newForm.Status = "等待RMA单号确认";
                //newForm.RunningNumber = RunningNumberService.GenerateApplicationNumber();

                //if (!product.ProductTypeReference.IsLoaded)
                //{
                //    product.ProductTypeReference.Load();
                //}
                //if (!product.ProblemTypeReference.IsLoaded)
                //{
                //    product.ProblemTypeReference.Load();
                //}

                //ApplicationProduct newproduct = new ApplicationProduct
                //{
                //    ProductType = product.ProductType,
                //    ProductCount = 1,
                //    ProductSerialNumber = returnProductSerialTextBox.Text,
                //    ProductVersionNumber = product.ProductVersionNumber,
                //    ProblemType = product.ProblemType,
                //    ProductProblemDescription = product.ProductProblemDescription,
                //    ProductAppearance = product.ProductAppearance,
                //    ProductPurchaseDateTime = product.ProductPurchaseDateTime,
                //    ProductRepairType = "保内"
                //};

                //newForm.ApplicationProduct.Add(newproduct);

                //long applicationID = appService.AddApplication(newForm);

                //appService.SubmitApplication(applicationID);

                // 发信
                if (!product.ApplicationFormReference.IsLoaded)
                {
                    product.ApplicationFormReference.Load();
                }
                //if (product.ApplicationForm.AgentID.HasValue)
                //{
                //    UserService userService = new UserService();
                //    User agent = userService.GetUserByID(product.ApplicationForm.AgentID.Value);
                //    string body = WebConfigurationManager.AppSettings["BJXXReturnProduct"];
                //    string emailBody = string.Format(body, contactLabel.Text, product.ReturnProductType);

                //    EmailService.SendEmail(agent.UserEmail, "备件先行发货", emailBody);
                //}

                if (isSendEmailChkBox.Checked)
                {
                    string[] emails = emailTxtBox.Text.Trim().Split(new char[] { '，', '，', ' ', ';', });
                    for (int index = 0; index < emails.Length; index++)
                    {
                        EmailService.SendEmail(emails[index], "备件先行收货", emailNoticeTxtBox.Text.Trim());
                    }
                }
                if (isSendSMS2ApplierChkBox.Checked)
                {
                    SMSService.SendSMS(SMS2ApplierTxtBox.Text.Trim(), applierPhoneTxtBox.Text.Trim());
                }
                if (isSendSMS2CustomerChkBox.Checked)
                {
                    SMSService.SendSMS(SMS2CustomerTxtBox.Text.Trim(), customerPhoneTxtBox.Text.Trim());
                }
                if (isSendSMS2SaleChkBox.Checked)
                {
                    string[] saleMobilePhone = salePhoneTxtBox.Text.Trim().Split(new char[] { '，', '，', ' ', ';', });
                    for (int index = 0; index < saleMobilePhone.Length; index++)
                    {
                        SMSService.SendSMS(SMS2SaleTxtBox.Text.Trim(), saleMobilePhone[index]);
                    }
                }
                Response.Write(string.Format("<script language='JavaScript'> alert( '备件已归还');location.href= 'BJXXListNeedConfirmReturn.aspx' </script>"));
            }
        }

    }
}
